<template>
  <div class="order-confirm-container" v-loading="loading">
    <div v-if="loading" class="loading-placeholder">
      <div class="spinner"></div>
      <p>正在加载订单信息...</p>
    </div>
    
    <div v-else-if="!order && !product" class="error-placeholder">
      <i class="el-icon-warning-outline"></i>
      <p>订单不存在或已被取消</p>
      <el-button type="primary" @click="goToProductList">返回商品列表</el-button>
    </div>
    
    <!-- 订单预览模式 -->
    <template v-else-if="product">
      <div class="order-confirm-header">
        <h1>订单确认</h1>
        <div class="preview-tag">订单预览</div>
      </div>
      
      <div class="order-confirm-content">
        <!-- 商品信息 -->
        <el-card class="order-info-card">
          <template #header>
            <div class="card-header">
              <span>商品信息</span>
            </div>
          </template>
          
          <div class="order-items">
            <div class="order-item">
              <div class="item-image">
                <img :src="product.coverImage || 'https://via.placeholder.com/80'" :alt="product.name">
              </div>
              <div class="item-info">
                <div class="item-name">{{ product.name }}</div>
                <div class="item-sku" v-if="product.sku">SKU: {{ product.sku }}</div>
              </div>
              <div class="item-price">
                ¥{{ product.price }}
              </div>
              <div class="item-quantity">
                x {{ quantity }}
              </div>
              <div class="item-total">
                ¥{{ (product.price * quantity).toFixed(2) }}
              </div>
            </div>
          </div>
          
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">商品总额:</span>
              <span class="value">¥{{ getSubtotal() }}</span>
            </div>
            <div class="summary-item">
              <span class="label">运费:</span>
              <span class="value">¥0</span>
            </div>
            <div class="summary-item">
              <span class="label">税费:</span>
              <span class="value">¥0</span>
            </div>
            <div class="summary-item total">
              <span class="label">总计:</span>
              <span class="value">¥{{ getTotalAmount() }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 配送信息 -->
        <el-card class="shipping-info-card">
          <template #header>
            <div class="card-header">
              <span>配送信息</span>
            </div>
          </template>
          
          <div class="shipping-address">
            <h3>收货地址</h3>
            <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="100px">
              <el-form-item label="收件人" prop="name">
                <el-input v-model="addressForm.name" placeholder="请输入收件人姓名"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
              </el-form-item>
              <el-form-item label="收货地址" prop="address">
                <el-input type="textarea" v-model="addressForm.address" placeholder="请输入完整收货地址" :rows="3"></el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="addressForm.sameAsBilling">账单地址与收货地址相同</el-checkbox>
              </el-form-item>
              <el-form-item label="账单地址" v-if="!addressForm.sameAsBilling" prop="billingAddress">
                <el-input type="textarea" v-model="billingAddress" placeholder="请输入账单地址" :rows="3"></el-input>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="shipping-method">
            <h3>配送方式</h3>
            <el-radio-group v-model="selectedShippingMethod">
              <el-radio label="标准快递">标准快递</el-radio>
              <el-radio label="加急配送">加急配送</el-radio>
              <el-radio label="顺丰特快">顺丰特快</el-radio>
            </el-radio-group>
          </div>
          
          <div class="order-notes">
            <h3>订单备注</h3>
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入订单备注（选填）"
              v-model="orderNotes">
            </el-input>
          </div>
        </el-card>
        
        <!-- 支付信息 -->
        <el-card class="payment-info-card">
          <template #header>
            <div class="card-header">
              <span>支付信息</span>
            </div>
          </template>
          
          <div class="payment-method">
            <h3>支付方式</h3>
            <div class="payment-method-selector">
              <el-radio-group v-model="selectedPaymentMethod">
                <el-radio label="ALIPAY">支付宝</el-radio>
                <el-radio label="WECHAT">微信支付</el-radio>
                <el-radio label="CREDITCARD">信用卡</el-radio>
              </el-radio-group>
            </div>
          </div>
          
          <div class="payment-options">
            <el-checkbox id="payNowCheckbox">创建订单后立即支付</el-checkbox>
          </div>
          
          <div class="payment-action">
            <el-button type="primary" size="large" @click="createNewOrder" :loading="paymentLoading">
              提交订单
            </el-button>
            <el-button type="default" size="large" @click="cancelOrder">
              取消
            </el-button>
          </div>
        </el-card>
      </div>
    </template>
    
    <!-- 已创建订单模式 -->
    <template v-else-if="order">
      <div class="order-confirm-header">
        <h1>订单确认</h1>
        <div class="order-number">订单号: {{ order.orderNumber }}</div>
      </div>
      
      <div class="order-confirm-content">
        <!-- 订单信息 -->
        <el-card class="order-info-card">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
              <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
            </div>
          </template>
          
          <div class="order-items">
            <div v-for="item in order.orderItems" :key="item.id" class="order-item">
              <div class="item-image">
                <img :src="item.productImage || 'https://via.placeholder.com/80'" :alt="item.productName">
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-sku" v-if="item.sku">SKU: {{ item.sku }}</div>
                <div class="item-options" v-if="item.options">
                  <span v-for="(value, key) in item.options" :key="key">
                    {{ key }}: {{ value }}
                  </span>
                </div>
              </div>
              <div class="item-price">
                ¥{{ item.unitPrice }}
              </div>
              <div class="item-quantity">
                x {{ item.quantity }}
              </div>
              <div class="item-total">
                ¥{{ (item.unitPrice * item.quantity).toFixed(2) }}
              </div>
            </div>
          </div>
          
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">商品总额:</span>
              <span class="value">¥{{ getSubtotal() }}</span>
            </div>
            <div class="summary-item">
              <span class="label">运费:</span>
              <span class="value">¥{{ order.shippingCost || 0 }}</span>
            </div>
            <div class="summary-item">
              <span class="label">税费:</span>
              <span class="value">¥{{ order.taxAmount || 0 }}</span>
            </div>
            <div class="summary-item total">
              <span class="label">总计:</span>
              <span class="value">¥{{ getTotalAmount() }}</span>
            </div>
          </div>
        </el-card>
        
        <!-- 配送信息 -->
        <el-card class="shipping-info-card">
          <template #header>
            <div class="card-header">
              <span>配送信息</span>
            </div>
          </template>
          
          <div class="shipping-address">
            <h3>收货地址</h3>
            <p>{{ order.shippingAddress }}</p>
          </div>
          
          <div class="shipping-method">
            <h3>配送方式</h3>
            <p>{{ order.shippingMethod }}</p>
          </div>
        </el-card>
        
        <!-- 支付信息 -->
        <el-card class="payment-info-card">
          <template #header>
            <div class="card-header">
              <span>支付信息</span>
            </div>
          </template>
          
          <div class="payment-method">
            <h3>支付方式</h3>
            <div class="payment-method-selector">
              <el-radio-group v-model="selectedPaymentMethod">
                <el-radio label="ALIPAY">支付宝</el-radio>
                <el-radio label="WECHAT">微信支付</el-radio>
                <el-radio label="CREDITCARD">信用卡</el-radio>
              </el-radio-group>
            </div>
          </div>
          
          <div class="payment-action">
            <el-button type="primary" size="large" @click="proceedToPayment" :loading="paymentLoading">
              立即支付 ¥{{ getTotalAmount() }}
            </el-button>
            <el-button type="default" size="large" @click="cancelOrder">
              取消订单
            </el-button>
          </div>
        </el-card>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getOrderById, getOrderByOrderNumber, updateOrderStatus, createOrder } from '../../../api/order';
import { useUserStore } from '../../../stores/user';
import productApi from '../../../api/product';

// 路由相关
const route = useRoute();
const router = useRouter();

// 数据
const loading = ref(true);
const paymentLoading = ref(false);
const order = ref(null);
const product = ref(null);
const quantity = ref(1);
const selectedPaymentMethod = ref('ALIPAY');
const selectedShippingMethod = ref('标准快递');
const userStore = useUserStore();
const addressForm = ref({
  name: '',
  phone: '',
  address: '',
  sameAsBilling: true  // 默认使用相同地址
});
const billingAddress = ref(''); // 账单地址
const addressRules = ref({
  name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  address: [{ required: true, message: '请输入完整收货地址', trigger: 'blur' }],
  billingAddress: [{ required: true, message: '请输入账单地址', trigger: 'blur' }]
});
const addressFormRef = ref(null);
const orderNotes = ref('');

// 获取完整地址字符串（包含收件人和手机）
const getFullAddress = () => {
  return `${addressForm.value.name} ${addressForm.value.phone} ${addressForm.value.address}`;
};

// 根据状态获取对应的类型
const getStatusType = (status) => {
  const statusMap = {
    'PENDING': 'warning',
    'PROCESSING': 'info',
    'SHIPPED': 'primary',
    'DELIVERED': 'success',
    'CANCELED': 'danger',
    'REFUNDED': 'danger',
    'PAYMENT_PENDING': 'warning',
    'PAYMENT_COMPLETED': 'success',
    'PAYMENT_FAILED': 'danger'
  };
  return statusMap[status] || 'info';
};

// 根据状态获取对应的文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待处理',
    'PROCESSING': '处理中',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'CANCELED': '已取消',
    'REFUNDED': '已退款',
    'PAYMENT_PENDING': '待支付',
    'PAYMENT_COMPLETED': '已支付',
    'PAYMENT_FAILED': '支付失败'
  };
  return statusMap[status] || '未知状态';
};

// 计算商品小计
const getSubtotal = () => {
  if (order.value && order.value.orderItems) {
    return order.value.orderItems.reduce((total, item) => {
      return total + (item.unitPrice * item.quantity);
    }, 0).toFixed(2);
  } else if (product.value) {
    return (product.value.price * quantity.value).toFixed(2);
  }
  return '0.00';
};

// 计算订单总金额
const getTotalAmount = () => {
  const subtotal = parseFloat(getSubtotal());
  const shipping = order.value?.shippingCost || 0;
  const tax = order.value?.taxAmount || 0;
  
  return (subtotal + shipping + tax).toFixed(2);
};

// 获取订单信息
const fetchOrder = async () => {
  loading.value = true;
  
  const orderId = route.query.orderId;
  const orderNumber = route.query.orderNumber;
  const productId = route.query.productId;
  
  try {
    // 如果有订单ID或订单号，获取已创建的订单
    if (orderId || orderNumber) {
      let response;
      
      if (orderId) {
        response = await getOrderById(orderId);
      } else if (orderNumber) {
        response = await getOrderByOrderNumber(orderNumber);
      }
      
      order.value = response.data;
      selectedPaymentMethod.value = order.value.paymentMethod || 'ALIPAY';
    } 
    // 如果有商品ID，获取商品信息（预览下单）
    else if (productId) {
      const result = await productApi.getProductById(productId);
      product.value = result.data;
      quantity.value = parseInt(route.query.quantity as string) || 1;
    } else {
      ElMessage.error('未提供有效的订单ID或商品信息');
      router.push('/user/home');
      return;
    }
  } catch (error) {
    console.error('获取信息失败:', error);
    ElMessage.error('获取信息失败');
    order.value = null;
    product.value = null;
  } finally {
    loading.value = false;
  }
};

// 创建订单
const createNewOrder = async () => {
  if (!product.value) return;
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login?redirect=' + encodeURIComponent(route.fullPath));
    return;
  }
  
  // 确保有customerId
  if (!userStore.customerId) {
    ElMessage.warning('无法获取客户ID，请重新登录');
    return;
  }
  
  // 表单验证
  let valid = false;
  await addressFormRef.value.validate((isValid) => {
    valid = isValid;
  });
  
  if (!valid) {
    ElMessage.warning('请完善收货地址信息');
    return;
  }
  
  // 确保账单地址不为空
  if (!addressForm.value.sameAsBilling && (!billingAddress.value || billingAddress.value.trim() === '')) {
    ElMessage.warning('账单地址不能为空，请填写账单地址或勾选"账单地址与收货地址相同"');
    return;
  }
  
  paymentLoading.value = true;
  
  // 准备订单数据
  const orderData = {
    customerId: userStore.customerId, // 使用登录时获取的客户ID
    orderItems: [{
      productId: product.value.id,
      productName: product.value.name,
      productImage: product.value.coverImage,
      quantity: quantity.value,
      unitPrice: product.value.price,
      sku: product.value.sku,
      options: {}
    }],
    shippingCost: 0, // 这里可以根据实际情况计算运费
    taxAmount: 0, // 税费
    paymentMethod: selectedPaymentMethod.value,
    shippingMethod: selectedShippingMethod.value,
    shippingAddress: getFullAddress(),
    billingAddress: addressForm.value.sameAsBilling ? getFullAddress() : billingAddress.value,
    notes: orderNotes.value
  };
  
  console.log('正在创建订单，请求数据：', orderData);
  
  try {
    // 调用创建订单API
    const response = await createOrder(orderData);
    
    // 订单创建成功
    ElMessage.success('订单创建成功');
    
    // 更新页面数据为新创建的订单
    order.value = response.data;
    product.value = null;
    
    // 如果选择立即支付，则进行支付
    if (document.getElementById('payNowCheckbox')?.checked) {
      await proceedToPayment();
    }
  } catch (error) {
    console.error('创建订单失败:', error);
    ElMessage.error('创建订单失败，请稍后重试');
  } finally {
    paymentLoading.value = false;
  }
};

// 支付订单
const proceedToPayment = async () => {
  if (!order.value || !order.value.id) {
    ElMessage.error('订单不存在');
    return;
  }
  
  paymentLoading.value = true;
  
  try {
    // 导航到支付页面，与"我的订单"页面使用相同的支付流程
    router.push(`/user/payment/${order.value.id}`);
  } catch (error) {
    console.error('支付流程异常:', error);
    ElMessage.error('处理支付请求时出错');
  } finally {
    paymentLoading.value = false;
  }
};

// 取消订单
const cancelOrder = async () => {
  if (product.value) {
    // 如果是预览状态，直接返回商品页
    router.back();
    return;
  }
  
  if (!order.value) return;
  
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 调用取消订单API
    await updateOrderStatus(order.value.id, 'CANCELED');
    
    ElMessage.success('订单已取消');
    router.push('/user/orders');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单失败');
    }
  }
};

// 跳转到商品列表
const goToProductList = () => {
  router.push('/user/products');
};

// 生命周期钩子
onMounted(() => {
  // 更详细的调试信息检查
  console.log('===== userStore状态详细信息 =====');
  console.log('登录状态:', userStore.isLoggedIn ? '已登录' : '未登录');
  console.log('用户ID:', userStore.userId);
  console.log('客户ID:', userStore.customerId);
  console.log('用户名:', userStore.username);
  console.log('localStorage中的token:', localStorage.getItem('token'));
  console.log('localStorage中的userId:', localStorage.getItem('userId'));
  console.log('localStorage中的customerId:', localStorage.getItem('customerId'));
  console.log('localStorage中的username:', localStorage.getItem('username'));
  console.log('isMerchant:', userStore.isMerchant);
  console.log('==================================');
  
  fetchOrder();
});
</script>

<style scoped>
.order-confirm-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-placeholder,
.error-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #409EFF;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.order-confirm-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-confirm-header h1 {
  margin: 0;
  font-size: 24px;
}

.order-number, .preview-tag {
  font-size: 16px;
  color: #666;
}

.preview-tag {
  background-color: #E6A23C;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
}

.order-confirm-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-items {
  margin-bottom: 20px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  flex: 0 0 80px;
  margin-right: 15px;
}

.item-image img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.item-sku,
.item-options {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.item-price,
.item-quantity,
.item-total {
  flex: 0 0 100px;
  text-align: right;
}

.item-total {
  font-weight: 500;
}

.order-summary {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: 500;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.shipping-info-card,
.payment-info-card {
  margin-top: 20px;
}

.shipping-address,
.shipping-method,
.payment-method {
  margin-bottom: 20px;
}

.shipping-address h3,
.shipping-method h3,
.payment-method h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.payment-method-selector,
.payment-options {
  margin-top: 15px;
}

.payment-options {
  margin-bottom: 20px;
}

.payment-action {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
}

@media (max-width: 768px) {
  .order-item {
    flex-wrap: wrap;
  }
  
  .item-image {
    flex: 0 0 60px;
  }
  
  .item-image img {
    width: 60px;
    height: 60px;
  }
  
  .item-price,
  .item-quantity,
  .item-total {
    flex: 1;
    text-align: left;
    margin-top: 10px;
  }
  
  .payment-action {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 